import React, {
  useState,
  useEffect,
  forwardRef,
  useRef,
  useImperativeHandle,
  useMemo,
} from 'react';
import _ from 'lodash';
import DefaultLoginForm from './loginForm';
import LoginFormWithPhone from './loginFormWithPhone';
// import LoginFormWithWechat from './loginFormWithWechat';
import { PhoneFilled, WechatOutlined } from '@ant-design/icons';
import defaultSettings from '@/../config/defaultSettings';
import appDescription from '@/../package.json';
import styles from '../index.less';

// 其他登录方式
const extraLoginForms = [
  {
    key: 'phone',
    icon: PhoneFilled,
    tip: '手机号登录',
    component: LoginFormWithPhone,
  },
  // {
  //   key: 'wechat',
  //   icon: WechatOutlined,
  //   tip: '微信登录',
  //   component: LoginFormWithWechat,
  // },
];

export default forwardRef(({ loginLoading, loginTypes, initialLoading, handleLogin }, ref) => {
  const formRef = useRef(null);
  const [baseFormRender, setBaseFormRender] = useState(true);
  const [extraFormRender, setExtraFormRender] = useState(false);
  const [activeExtraLoginType, setActiveExtraLoginType] = useState(null);
  const [renderExtraLoginType, setRenderExtraLoginType] = useState(null);

  // 额外的登录方式
  const loginTypeList = useMemo(() => {
    return _.map(extraLoginForms, ({ key, component, ...restProps }) => ({
      key,
      ...restProps,
      disabled: !_.includes(loginTypes, key),
    }));
  }, [loginTypes]);

  // ref方法挂载
  useImperativeHandle(ref, () => ({
    errorHandle: (...args) => {
      const { errorHandle } = formRef.current || {};
      errorHandle && errorHandle(...args);
    },
    updateValidCode: () => {
      const { updateValidCode } = formRef.current || {};
      updateValidCode && updateValidCode();
    },
  }));

  // 表单卸载
  useEffect(() => {
    if (activeExtraLoginType) {
      setExtraFormRender(true);
      setTimeout(() => {
        setBaseFormRender(false);
      }, 400);
    } else {
      setBaseFormRender(true);
      setTimeout(() => {
        setExtraFormRender(false);
        setRenderExtraLoginType(null);
      }, 400);
    }
  }, [activeExtraLoginType]);

  // 登录
  const handleLoginAction = (params) => {
    handleLogin({ type: activeExtraLoginType, params });
  };

  return (
    <div className={styles.loginFormContainer}>
      <div className={styles.loginPageTitle}>
        <span className={styles.loginPageTitleText}>
          {defaultSettings.title || appDescription.name}
        </span>
      </div>
      <div className={styles.formTransferWrapper}>
        <div
          className={`${styles.formTransferPreviewItem} ${
            !!activeExtraLoginType ? styles.begin : styles.end
          } ${!!activeExtraLoginType ? styles.previewInactive : styles.previewActive}`}
        >
          {baseFormRender && (
            <DefaultLoginForm
              ref={formRef}
              loginDisabled={extraFormRender}
              loginLoading={loginLoading}
              loginTypeList={loginTypeList}
              initialLoading={initialLoading}
              setLoginType={(nextType) => {
                setActiveExtraLoginType(nextType || null);
                setRenderExtraLoginType(nextType || null);
              }}
              handleLogin={handleLoginAction}
            />
          )}
        </div>
        <div
          className={`${styles.formTransferPreviewItem} ${
            !activeExtraLoginType ? styles.begin : styles.end
          } ${!!activeExtraLoginType ? styles.backActive : styles.backInactive}`}
        >
          {extraFormRender &&
            React.createElement(
              _.find(extraLoginForms, ({ key }) => key === renderExtraLoginType)?.component ||
                'div',
              {
                ref: formRef,
                loginLoading,
                loginDisabled: baseFormRender,
                handleLogin: handleLoginAction,
                turnBack: () => {
                  setActiveExtraLoginType(null);
                },
              },
            )}
        </div>
      </div>
    </div>
  );
});
